<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:fb="http://ogp.me/ns/fb"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <div id="fb-root"></div>
        <script src="//connect.facebook.net/es_ES/all.js"></script>
        <script>
            window.fbAsyncInit = function() {
                FB.init({
                    //appId      : '1388008284748084', // App ID
                    appId      : '212044188860269', // App ID
                    //channelUrl : '//feverapp.herokuapp.com', // Channel File
                    status     : true, // check login status
                    cookie     : true, // enable cookies to allow the server to access the session
                    xfbml      : true  // parse XFBML
                });

                // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
                // for any authentication related change, such as login, logout or session refresh. This means that
                // whenever someone who was previously logged out tries to log in again, the correct case below 
                // will be handled. 
                FB.Event.subscribe('auth.authResponseChange', function(response) {
                    // Here we specify what we do with the response anytime this event occurs. 
                    if (response.status === 'connected') {
                        // The response object is returned with a status field that lets the app know the current
                        // login status of the person. In this case, we're handling the situation where they 
                        // have logged in to the app.
                        testAPI();
                    } else if (response.status === 'not_authorized') {
                        // In this case, the person is logged into Facebook, but not into the app, so we call
                        // FB.login() to prompt them to do so. 
                        // In real-life usage, you wouldn't want to immediately prompt someone to login 
                        // like this, for two reasons:
                        // (1) JavaScript created popup windows are blocked by most browsers unless they 
                        // result from direct interaction from people using the app (such as a mouse click)
                        // (2) it is a bad experience to be continually prompted to login upon page load.
                        FB.login();
                    } else {
                        // In this case, the person is not logged into Facebook, so we call the login() 
                        // function to prompt them to do so. Note that at this stage there is no indication
                        // of whether they are logged into the app. If they aren't then they'll see the Login
                        // dialog right after they log in to Facebook. 
                        // The same caveats as above apply to the FB.login() call here.
                        FB.login();
                    }
                });
            };

            // Load the SDK asynchronously
            (function(d){
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));

            // Here we run a very simple test of the Graph API after login is successful. 
            // This testAPI() function is only called in those cases. 
            function testAPI() {
                console.log('Welcome!  Fetching your information.... ');
                FB.api('/me', function(response) {
                    console.log('Good to see you, ' + response.name + '.');
                });
            }
        </script>

        <fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
        <script src="http://connect.facebook.net/en_US/all.js"></script>
        <h:form id="form">
            <p:selectManyCheckbox id="checks" value="#{fbController.selectedFB}" layout="pageDirection">  
                <f:selectItems value="#{fbController.fb}" /> 
                <input type="button" onclick="sendRequestViaMultiFriendSelectorSelected(); return false;" value="Send Request to Many Users with MFS" />
            </p:selectManyCheckbox>
        </h:form>

        <p>
            <input type="button"
                   onclick="sendInvitation(); return false;"
                   value="Send Request to Users Directly"
                   />
            <input type="text" value="User ID" name="user_ids" />
        </p>

        <!--onclick="sendRequestToRecipients(); return false;"-->

        <!--<p>
            <input type="button"
                   onclick="sendRequestViaMultiFriendSelector(); return false;"
                   value="Send Request to Many Users with MFS"
                   />
        </p>-->

        <script type="text/javascript">
            var at;
            $(document).ready(function () {

                FB.init({ 
                    appId: '212044188860269', 
                    cookie: true, 
                    xfbml: true, 
                    status: true });

                FB.getLoginStatus(function (response) {
                    if (response.authResponse) {
                        $('#AccessToken').val(response.authResponse.accessToken);
                    } else {
                        // do something...maybe show a login prompt
                    }
                });
            });
                        
            function getAppUsers(callback){
                var apiQuery = 
                    {
                    method: 'fql.query',
                    query: 'SELECT uid, name, username FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2 = me() ) AND is_app_user'
                } 

                FB.api(apiQuery, function(response){
                    var s = response.length;
                    var app_users = new Array(s);
                    for(var i=0; i != s; i++){
                        app_users[i] = response[i].username;
                    }
                    callback(app_users);
                });
            }
            
            function sendRequestViaMultiFriendSelectorSelected() {
                var chs = document.getElementsByName("form:checks");
                var users = new Array();
                var no_users = "";
                var u=-1;
                var first = true;
                getAppUsers(function(res){
                    var p = chs.length;
                    var fb;
                    for(var i = 0; i != p;i++){
                        if(chs[i].checked){
                            fb = chs[i].value;
                            if(res.indexOf(fb)>-1){
                                if(u==-1) u=0;
                                users[u] = fb;
                                u++;
                                //console.log('Encontrado '+fb);
                            }else{
                                if(first){
                                    no_users = fb;
                                    first = false;
                                }else{
                                    no_users += ","+fb;
                                }
                                //console.log('No found '+fb);
                            }
                        }
                    }                 

                    /*if(u>-1){
                        console.log('Send invitations to: '+users);
                        for(var i=0; i != u; i++){
                            FB.api(
                            '/'+users[i]+'/notifications?access_token=151779115008427|jxyecAH6JoIWkRSIb6aVdP84xWk&amp;template=Te han invitado a Fabrik este Sábado&amp;href=?index.html',
                            'post');
                        }
                    }*/
        
                    if(u>-1){
                        console.log('Send invitations to: '+users);
                        for(var i=0; i != u; i++){
                            FB.api(
                            //'/'+users[i]+'/notifications?access_token=1388008284748084|pFmhPnALWJCDEeIbh06yvMlDcVc&amp;template=Te han invitado a Fabrik este Sábado&amp;href=?index.html',
                            '/'+users[i]+'/notifications?access_token=212044188860269|Oz1dR59MBTuYD2GJVhFq-XCZHLA&amp;template=Te han invitado a Fabrik este Sábado&amp;href=#',
                            'post');
                        }
                    }

                    if(no_users != ""){
                        console.log('Send app request to: '+no_users);
                        FB.ui({method: 'apprequests',
                            message: 'Invitation to use Fever !!',
                            to: no_users,
                            data: 'Congratulations. You were invited to use Fever',
                            title:'Fever Invitation'},function(res){});
                    }
                });
                
                /*FB.api(
                '/'+fb+'/notifications?access_token=151779115008427|jxyecAH6JoIWkRSIb6aVdP84xWk&amp;template=Te han invitado a Fabrik este Sábado&amp;href=?index.html',
                'post');
                
                FB.ui({method: 'apprequests',
                                    message: 'Invitation to use Fever !!',
                                    to: fb,
                                    data: 'Congratulations. You were invited to use Fever',
                                    title:'Fever Invitation'});
                 */                    
                    
                /*console.log('Test');
                        //console.log(app_user);
                        var chs = document.getElementsByName("form:checks");
                        var p = chs.length;
                        var fb;
                        for(var i = 0; i != p;i++){
                            if(chs[i].checked){
                                fb = chs[i];
                                FB.ui({method: 'apprequests',
                                    message: 'Invitation to Nells !!',
                                    data: 'Let\'s party!',
                                    title:'Fever Invitation'
                                }, function(response){
                                    console.log(response);

                                });*/
                        
                        
                /*FB.ui({method: 'send',
                            message: 'El menda te ha invitado a Nells',
                            to: fb,
                            description: 'Mensaje de prueba',
                            link: 'http://www.nytimes.com/2011/06/15/arts/people-argue-just-to-win-scholars-assert.html?_r=0',
                            new_style_message:true
                        }, requestCallback);*/
                /*alert('sent message');
                    }
                }                
                alert(fb);*/
            }

            function sendInvitation(){
                var i=0;
                for (i; i!=2; i++){
                    if(i==0){
                        /*FB.api(
                        '/JLBarreche/notifications?access_token=151779115008427|jxyecAH6JoIWkRSIb6aVdP84xWk&amp;template=@[1521157793] te desea un feliz Martes!&amp;href=?index.html',
                        //'/100006169112584/notifications?template=Ola',
                        'post',
                        function(response){
                            alert(response.error[0].message);
                        });*/
                    }else if (i==1){
                        FB.api(
                        '/armando.amador.969/notifications?access_token=151779115008427|jxyecAH6JoIWkRSIb6aVdP84xWk&amp;template=@[100006209284802] te autodeseas un feliz Martes! Marginado&amp;href=?index.html',
                        //'/100006169112584/notifications?template=Ola',
                        'post',
                        function(response){
                            alert(response.error[0].message);
                        });
                    }
                }
            }

            function sendRequestToRecipients() {
                var user_ids = document.getElementsByName("user_ids")[0].value;
                FB.ui({method: 'apprequests',
                    message: 'My Great Request',
                    to: user_ids
                }, requestCallback);
            }

            function sendRequestViaMultiFriendSelector() {
                FB.ui({method: 'apprequests',
                    message: 'Invitation to Nells !!',
                    data: 'Let\'s party!',
                    title:'Fever Invitation'
                }, function(response){
                    alert('Ola!');
                    console.log('K ase');
                    console.log(response);
                    test();
                    /*var idsLength = response.request_ids.length;
                    console.log(idsLength);
                    
                    var idList = "";
                    var data = {};
                    var ajaxSettings = {};
                    for (var i = 0; i != idsLength; i++){
                        idList += response.request_ids[i];
                        if (i != idsLength-1){
                            idList += ",";
                        }
                    }
                    alert('Number: '+idsLength);
                    alert('Ids: '+idList);*/
                });
            }
            
            function addPlan(){
                FB.api(
                'me/feverapp_test:inivitar',
                'post',
                {
                    lugar: "me"
                },
                function(response) {
                    // handle the response
                }
            );
                
                FB.api(
                'me/objects/feverapp_test:lugar',
                'post',
                {
                    app_id: '151779115008427',
                    type: "feverapp_test:lugar",
                    url: "http://www.grupo-kapital.com/fabrik/",
                    title: "Fabrik",
                    image: "http://www.emoxion.com/tmp/discotecas/1191882851logo_fabrik01.jpg",
                    location: "http://goo.gl/maps/BRjrT",
                    description: "Fiesta de inauguracion de Fever en Fabrik"
                },
                function(response) {
                    //alert(response.title);
                }
            );
            }
            
            function friends(){
                var us = new Array();
                var i = 0;
                var k = 0;
                FB.api(
                'fql',
                {q: 'SELECT uid, name, sex, birthday_date, interests, music, movies, relationship_status FROM user WHERE uid in (SELECT uid2 FROM friend WHERE uid1=me())'},
                function(response)
                {
                    alert(response);
                    /*alert(response.data[k].uid);
                    alert(response.data[k].name);
                    alert(response.data[k].sex);*/
                    alert(response.data[k].birthday_date);
                    /*alert(response.data[k].interests);
                    alert(response.data[k].music);
                    alert(response.data[k].movies);
                    alert(response.data[k].relationship_status);*/


                    /*$.each(response.data,function(index,us) {
                            //alert(us.name + ' has id:' + us.uid);
                            us[i] = us.name;
                            //na[i] = friend.username
                            i++;
                        });*/
                    //alert('Your name is ' + response.data[3].name + ' and username: ' + response.data[3].username);
                });
                //alert(us);
            }
            
            
            
            function getFriends(){
                var us = new Array();
                var na = new Array();
                FB.api('/me/friends?fields=name,username,location', function(response) {
                    var ids='';
                    var i = 0;
                    if(response.data) {
                        $.each(response.data,function(index,friend) {
                            //alert(friend.name + ' has id:' + friend.id + ' and FB id:' + friend.location);
                            us[i] = friend.id;
                            na[i] = friend.username
                            i++;
                        });
                        alert(us);
                        alert(na);
                    } else {
                        alert("Error!");
                    }
                });
            }
            
            function requestCallback(response) {
                // Handle callback here
                //alert(result);
                var ids = response["to"];
                alert('Test: '+ids);
                for (var i = 0; i != ids.length; ++i)
                {
                    //"ids[i]" is what you want.
                    alert(ids[i]);
                }
            }
            
            /*function onRequestDelete(result, fail){
                if(result == null){
                    trace('Delete Request failed');
                }else{
                    trace('Delete Request success');
                }
            }*/ 
        </script>
    </h:body>
    <!--<script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
        FB.init({
            appId:'151779115008427',
            cookie:true,
            status:true,
            xfbml:true
        });

        function FacebookInviteFriends()
        {
            FB.ui({
                method: 'apprequests',
                message: 'Your Message dialog',
            });
        }
    </script>

    <script type='text/javascript'>
        if (top.location!= self.location)
        {
            top.location = self.location
        }
    </script>


    //HTML Code
    <div id="fb-root"></div>
    <a href='#' onclick="FacebookInviteFriends();"> 
        Facebook Invite Friends Link
    </a>
</h:body>-->
</html>

